package com.sdut.material.controller;

import com.sdut.material.util.JSONResult;
import com.sdut.material.util.MD5Util;
import com.sdut.material.util.VerifyCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {
    @RequestMapping("/getLoginPage")
    public String getLoginPage() {
        return "login";
    }
    @RequestMapping("/getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(4);
        session.setAttribute("code",code);
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("image/png");
        VerifyCodeUtils.outputImage(220,60,os,code);
    }
    @ResponseBody
    @RequestMapping("/login")
    public JSONResult login(String username,String password,String code,HttpSession session) {
        String salt = "sdut";
        String password1 = MD5Util.MD5Encode(password + salt);
        String codeInfo = (String) session.getAttribute("code");
        if (StringUtils.isEmpty(code)) {
            System.out.println("1"+code);
            return JSONResult.error("验证码不能为空");
        }
        if ( !codeInfo.equalsIgnoreCase(code)) {
            return JSONResult.error("验证码错误");
        }
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            System.out.println("2"+code);
            return JSONResult.error("帐号或者密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password1);
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return JSONResult.error("用户名不存在");
        } catch (AuthenticationException e) {
            return JSONResult.error("用户名或者密码错误");
        } catch (AuthorizationException e) {
            return JSONResult.error("没有权限");
        }
        return JSONResult.ok("登录成功");
    }
}
